package cn.com.interceptor;

import cn.com.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p>Project:AcademicSystem - LoginFilter
 *
 * @author 黄俊玮 On Administrator
 * @version 1.0
 * @DataTime 2024/6/13 17:45:12
 * @since 1.8
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("------过滤器工作---------");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        User lgoinUser = (User) session.getAttribute("loginState");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String path = request.getServletPath();



        if (session.getAttribute("loginState") == null){
            if (request.getServletPath().equals("/index/login.do")){
                filterChain.doFilter(request,servletResponse);
                return;
            }
            request.getRequestDispatcher("/out.do").forward(request,response);
        }
        else if (path.contains("/index/"))filterChain.doFilter(request,servletResponse);
        else if (lgoinUser.getRole() == 0 && path.contains("/Administrator/"))filterChain.doFilter(request,servletResponse);
        else if (lgoinUser.getRole() == 1 && path.contains("/student/"))filterChain.doFilter(request,servletResponse);
        else if (lgoinUser.getRole() == 2 && path.contains("/teacher/"))filterChain.doFilter(request,servletResponse);
        else {
            request.getRequestDispatcher("/out.do").forward(request,response);
        }




    }

    @Override
    public void destroy() {

    }
}
